package com.liuxin.zhiyuan.shujuzhongxin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuxin.zhiyuan.shujuzhongxin.domain.po.SchoolScoreLinesEntity;
import com.liuxin.zhiyuan.shujuzhongxin.mapper.YuanxiaoinfoMapper;
import com.liuxin.zhiyuan.shujuzhongxin.domain.dto.YuanxiaoListDTO;
import com.liuxin.zhiyuan.shujuzhongxin.domain.po.YuanxiaoinfoEntity;
import com.liuxin.zhiyuan.shujuzhongxin.service.SchoolScoreLinesService;
import com.liuxin.zhiyuan.shujuzhongxin.service.YuanxiaoinfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuxin.common.utils.PageUtils;
import org.apache.commons.lang.StringUtils;

@Slf4j
@Service
public class YuanxiaoinfoServiceImpl extends ServiceImpl<YuanxiaoinfoMapper, YuanxiaoinfoEntity> implements YuanxiaoinfoService {

    @Autowired
    private SchoolScoreLinesService schoolScoreLinesService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<YuanxiaoinfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name", "logo_url", "is_985","is_211","is_dfc","is_imp_prov","is_imp_country","school_type","is_gov","attach","prov_short","city_short");
        // 处理查询条件
        if (params.containsKey("name") && StringUtils.isNotBlank((String) params.get("name"))) {
            queryWrapper.like("name", (String) params.get("name"));
        }
        if (params.containsKey("is985") && StringUtils.isNotBlank((String) params.get("is985"))) {
            queryWrapper.eq("is_985", params.get("is985"));
        }
        if (params.containsKey("is211") && StringUtils.isNotBlank((String) params.get("is211"))) {
            queryWrapper.eq("is_211", params.get("is211"));
        }
        if (params.containsKey("isDfc") && StringUtils.isNotBlank((String) params.get("isDfc"))) {
            queryWrapper.eq("is_dfc", params.get("isDfc"));
        }
        if (params.containsKey("isImpProv") && StringUtils.isNotBlank((String) params.get("isImpProv"))) {
            queryWrapper.eq("is_imp_prov", params.get("isImpProv"));
        }
        if (params.containsKey("isImpCountry") && StringUtils.isNotBlank((String) params.get("isImpCountry"))) {
            queryWrapper.eq("is_imp_country", params.get("isImpCountry"));
        }
        if (params.containsKey("schoolType") && StringUtils.isNotBlank((String) params.get("schoolType"))) {
            queryWrapper.eq("school_type", params.get("schoolType"));
        }
        if (params.containsKey("isGov") && StringUtils.isNotBlank((String) params.get("isGov"))) {
            queryWrapper.eq("is_gov", params.get("isGov"));
        }
        if (params.containsKey("provShort") && StringUtils.isNotBlank((String) params.get("provShort"))) {
            queryWrapper.eq("prov_short", params.get("provShort"));
        }
        // 手动处理分页参数
        long current = 1;
        long size = 10;
        if (params.get("pageNum") != null) {
            current = Long.parseLong(params.get("pageNum").toString());
        }
        if (params.get("pageSize") != null) {
            size = Long.parseLong(params.get("pageSize").toString());
        }
        // 创建分页对象
        Page<YuanxiaoinfoEntity> page = new Page<>(current, size);
        // 执行分页查询
        IPage<YuanxiaoinfoEntity> resultPage = this.page(page, queryWrapper);
        log.info("分页查询结果: 总记录数={}, 当前页记录数={}, 页码={}, 页大小={}",
                resultPage.getTotal(), resultPage.getRecords().size(),
                resultPage.getCurrent(), resultPage.getSize());
        // 转换为DTO列表，只包含id和is985字段
        List<YuanxiaoListDTO> dtoList = resultPage.getRecords().stream()
                .map(entity -> {
                    YuanxiaoListDTO dto = new YuanxiaoListDTO();
                    dto.setId(entity.getId());
                    dto.setName(entity.getName());
                    dto.setLogoUrl(entity.getLogoUrl());
                    dto.setIs985(entity.getIs985());
                    dto.setIs211(entity.getIs211());
                    dto.setIsDfc(entity.getIsDfc());
                    dto.setIsImpProv(entity.getIsImpProv());
                    dto.setIsImpCountry(entity.getIsImpCountry());
                    dto.setSchoolType(entity.getSchoolType());
                    dto.setIsGov(entity.getIsGov());
                    dto.setAttach(entity.getAttach());
                    dto.setProvShort(entity.getProvShort());
                    dto.setCityShort(entity.getCityShort());
                    return dto;
                })
                .collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(dtoList, (int) resultPage.getTotal(), (int) resultPage.getSize(), (int) resultPage.getCurrent());
        return pageUtils;
    }

    @Override
    public YuanxiaoinfoEntity getSchoolWithScoreLines(Long id) {
        // 1. 查询学校基本信息
        YuanxiaoinfoEntity school = this.getById(id);
        if (school == null) {
            return null;
        }
        // 2. 查询该学校的历年分数线
        List<SchoolScoreLinesEntity> scoreLines = schoolScoreLinesService.list(
                new QueryWrapper<SchoolScoreLinesEntity>()
                        .eq("school_id", id)
                        .orderByDesc("year") // 按年份倒序排列
        );
        // 3. 将分数线列表转换为JSON字符串
        if (scoreLines != null && !scoreLines.isEmpty()) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                String scoreLinesJson = objectMapper.writeValueAsString(scoreLines);
                school.setSchoolScoreLines(scoreLinesJson);
            } catch (JsonProcessingException e) {
                // 如果JSON转换失败，设置默认值
                school.setSchoolScoreLines("[]");
                e.printStackTrace();
            }
        } else {
            // 如果没有分数线数据，设置为空数组
            school.setSchoolScoreLines("[]");
        }
        return school;
    }

}